import router from "@/router";
import { Message, Loading } from "./element";

export const fetchData = async (api, params, isLoading = true) => {
  if (isLoading) Loading.show();
  return api(params)
    .then((result) => {
      if (result.code == "0") {
        if (isLoading) Loading.close();
        if (result.message == "未支付" || result.message == "支付成功") {
          return Promise.resolve(result);
        }
        return Promise.resolve(result?.data);
      } else {
        Message.error(result.message);
        // Message.error("服务出错，请稍后重试！");
        // if(result.message == '登录信息不匹配，请重新登录!') {
        //   localStorage.clear();
        //   router.push("/index");
        // }
        return Promise.reject(result);
      }
    })
    .catch((err) => {
      if (isLoading) Loading.close();
      throw err;
    });
};

export const fetchService = async (url, param) => {
  const token = localStorage.getItem("userinfo")
    ? JSON.parse(localStorage.getItem("userinfo")).authToken
    : "";
  const response = await fetch(process.env.VUE_APP_BASE_URL + url, {
    method: "POST",
    timeout: 60000,
    headers: { "Content-Type": "application/json", Authtoken: token },
    body: JSON.stringify(param),
  });
  if (response.body || response.body.code == 0) {
    return response.body;
  } else {
    Message.error(response.message);
    // if(result.message == '登录信息不匹配，请重新登录!') {
    //   localStorage.clear();
    //   router.push("/index");
    // }
    // Message.error("服务出错，请稍后重试！");
    return;
  }
};

export const fetchGetService = async (url, params) => {
  if (params) {
    let paramsArray = [];
    //拼接参数
    Object.keys(params).forEach((key) =>
      paramsArray.push(key + "=" + params[key])
    );
    if (url.search(/\?/) === -1) {
      url += "?" + paramsArray.join("&");
    } else {
      url += "&" + paramsArray.join("&");
    }
  }
  const token = localStorage.getItem("userinfo")
    ? JSON.parse(localStorage.getItem("userinfo")).authToken
    : "";
  const response = await fetch(process.env.VUE_APP_BASE_URL + url, {
    method: "GET",
    timeout: 60000,
    headers: { Authtoken: token },
  });
  if (response.body || response.body.code == 0) {
    return response.body;
  } else {
    Message.error(response.message);
    // if(result.message == '登录信息不匹配，请重新登录!') {
    //   localStorage.clear();
    //   router.push("/index");
    // }
    // Message.error("服务出错，请稍后重试！");
    return;
  }
};

// 登出
export const loginOut = () => {
  const env = process.env.NODE_ENV;
  setTimeout(() => {
    if (env === "local") {
      router.push("/index");
    }
  }, 500);
};

export function deepTrim(obj) {
  if (!obj) return;
  return Object.keys(obj).reduce((pre, key) => {
    if (obj[key]?.toString === "[object Object]") {
      pre[key] = deepTrim(obj[key]);
    } else {
      pre[key] = typeof obj[key] === "string" ? obj[key].trim() : obj[key];
    }
    return pre;
  }, {});
}

export function copy(text) {
  // text是复制文本
  // 创建input元素
  const el = document.createElement("input");
  // 给input元素赋值需要复制的文本
  el.setAttribute("value", text);
  // 将input元素插入页面
  document.body.appendChild(el);
  // 选中input元素的文本
  el.select();
  // 复制内容到剪贴板
  document.execCommand("copy");
  // 删除input元素
  document.body.removeChild(el);
  Message.success("复制成功");
}
